package com.example.bysj_sb.dao;

import com.example.bysj_sb.domain.authority.Resource;
import com.example.bysj_sb.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository("resourceDao")
public class ResourceDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RoleService roleService;
    //增加
    public boolean add(Resource resource) {
        String sql = "INSERT INTO resource (description, url, no, role_id) VALUES (?, ?, ?, ?)";
        int affectedRowNum = jdbcTemplate.update(sql, resource.getNo(),
                resource.getDescription(),resource.getUrl(),resource.getNo(),resource.getRole().getId());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
    //通过定义内部类来返回查询结果
    public class ResourceRowMapper implements RowMapper<Resource> {
        @Override
        public Resource mapRow(ResultSet resultSet, int i) throws SQLException {
            Resource resource = new Resource();
            resource.setId(resultSet.getInt("id"));
            resource.setDescription(resultSet.getString("description"));
            resource.setNo(resultSet.getString("no"));
            resource.setUrl(resultSet.getNString("url"));
            resource.setRole(roleService.find(resultSet.getInt("role_id")));
            return resource;
        }
    }

    public Resource find(int id){
        String sql = "SELECT * FROM Resource WHERE id = ?";
        List<Resource> resources = jdbcTemplate.query(sql, new Object[]{id}, new ResourceRowMapper());
        if(!resources.isEmpty()){
            return resources.get(0);
        } else
            return null;
    }

    public List<Resource> findAll(){
        String sql = "SELECT * FROM Resource";
        List<Resource> resources = jdbcTemplate.query(sql, new ResourceRowMapper());
        return resources;
    }
    public boolean update(Resource resource) {
        String sql = "UPDATE Resource SET no = ? ,description=? WHERE id = ?";
        int affectedRowNum = jdbcTemplate.update(sql, resource.getNo(), resource.getDescription(), resource.getId());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
    public boolean delete(int id){
        String sql = "DELETE FROM Resource WHERE id = ? ";
        int affectedRowNum = jdbcTemplate.update(sql,id);
        if (affectedRowNum!=1){
            return false;
        }else{
            return true;
        }
    }
}
